package com.axonactive.yolo.validation;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.axonactive.yolo.domain.User;
import com.axonactive.yolo.domain.UserEmail;
import com.axonactive.yolo.dto.LoginParameters;
import com.axonactive.yolo.service.interfaces.UserEmailService;
import com.axonactive.yolo.util.EncryptDecrypt;
import com.axonactive.yolo.util.Utils;

@Component
public class LoginValidator implements Validator {

	private static Logger LOGGER = Logger.getLogger(LoginValidator.class);

	@Autowired
	private UserEmailService userEmailService;

	@Override
	public boolean supports(Class<?> clazz) {
		return LoginParameters.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		LoginParameters loginParams = (LoginParameters) target;

		ValidationUtils.rejectIfEmpty(errors, "userEmail", "email.notnull");
		ValidationUtils.rejectIfEmpty(errors, "password", "password.notnull");
		if (loginParams.getUserEmail().length() > 100) {
			errors.rejectValue("userEmail", "email.outOfRange");
		}
		if (!"".equals(loginParams.getUserEmail())
				&& !Utils.isValidEmail(loginParams.getUserEmail())) {
			errors.rejectValue("userEmail", "email.invalid");
		}
		if (loginParams.getPassword().length() > 50) {
			errors.rejectValue("password", "password.outOfRange");
		}
		// valid pass and email
		if (!"".equals(loginParams.getUserEmail())
				&& !"".equals(loginParams.getPassword())) {
			String email = loginParams.getUserEmail();
			String pass_encrypted = "";
			pass_encrypted = EncryptDecrypt.encryptMD5((loginParams
					.getPassword().trim()));

			UserEmail userEmail = userEmailService.findByEmailString(email);
			if (userEmail == null) {
				errors.rejectValue("userEmail", "email.password.wrong");
			} else if (!userEmail.isPrimary()) {
				errors.rejectValue("userEmail", "email.password.wrong");
				//
			} else {
				User user = userEmail.getUser();
				if (user == null) {
					errors.rejectValue("userEmail", "email.password.wrong");
				} else if (user.getPassword().equals(pass_encrypted)) {
					// login success
					LOGGER.info("id_found=" + user.getId());
				} else {
					errors.rejectValue("userEmail", "email.password.wrong");
				}
			}
		}

	}

}
